package juc.flowcontrol.aqsinstance;

import org.omg.PortableServer.THREAD_POLICY_ID;

import java.util.HashMap;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author fangbin
 * @desc
 * @date 2020/6/29 7:09
 */
public class OneShotLatch {


    private Sync sync = new Sync();

    public void await(){
        sync.acquireShared(0);
    }

    public void release(){
        sync.releaseShared(0);
    }



    class  Sync extends AbstractQueuedSynchronizer{
        @Override
        protected int tryAcquireShared(int arg) {
            return (getState()==1)?1:-1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            setState(1);
            return true;
        }
    }

    public static void main(String[] args) {

        OneShotLatch  oneShotLatch = new OneShotLatch();
        System.out.println(oneShotLatch);
        for(int i=0;i<5;i++){
            new Thread(()->{
                System.out.println(Thread.currentThread()+"等待出发");
                oneShotLatch.await();
                System.out.println(Thread.currentThread()+"开闸放行，开始出发");
            }).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        oneShotLatch.release();
    }
}
